package com.fc.utils;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.fc.properties.AliossProperties;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

@Component
@RequiredArgsConstructor
public class AliossUtil {
    private final AliossProperties aliossProperties;

    public String upload(MultipartFile file) {
        String originalFilename = file.getOriginalFilename();
        String fileName = String.format("%s%s", UUID.randomUUID(), originalFilename.substring(originalFilename.lastIndexOf(".")));
        OSS ossClient = getOSS();
        try {
            InputStream inputStream = file.getInputStream();
            ossClient.putObject(aliossProperties.getBucketName(), fileName, inputStream);
        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        } catch (ClientException ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }

        return new StringBuilder("https://")
                .append(aliossProperties.getBucketName())
                .append(".")
                .append(aliossProperties.getEndpoint())
                .append("/")
                .append(fileName)
                .toString();
    }

    private OSS getOSS() {
        return new OSSClientBuilder().build(String.format("https://%s", aliossProperties.getEndpoint()), aliossProperties.getOssAccessKeyId(), aliossProperties.getOssAccessKeySecret());
    }

    public void fileDelete(String filePath) {
        OSS oss = getOSS();
        String fileName = filePath.substring(filePath.lastIndexOf("/") + 1);
        int index = fileName.indexOf("?");
        try {
            oss.deleteObject(aliossProperties.getBucketName(), index == -1 ? fileName : fileName.substring(0, index));
            System.out.println("文件删除成功。");
        } catch (Exception e) {
            System.out.println("文件删除失败：" + e.getMessage());
        } finally {
            if (oss != null) {
                oss.shutdown();
            }
        }
    }
}
